import {
	createStore
} from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import {
	customerOpercustApi, getUserProfileApi, logoutApi, getUserRoleApi, getPermsApi
} from '@/apis/login.js'
const store = createStore({
	state: {
		token: {},
		userinfo: {}, // 用户信息
		customerinfo: {}, // 客户信息
		custid: "",
		userid: null,
		roles: [], // 用户角色信息
		perms: [], // 用户权限信息
		isExternal: false // 是否外部客户
	},
	mutations: {
		setToken (state, token) {
			state.token = token
		},
		setcustomerinfoInfo (state, info) {
			state.customerinfo = info
			state.custid = info.id
		},
		setUserInfo (state, info) {
			state.userid = info.userId
			state.userinfo = info
		},
		quitLogin (state) {
			state.token = ''
			state.userinfo = {}
			state.customerinfo = {}
			state.isExternal = false
			uni.reLaunch({
				url: "/pages/login/login",
			})
		},
		setRoles (state, roles) {
			state.roles = roles
			state.isExternal = roles.roles[0].roleKey === 'outperson'
		},
		setPerms (state, perms) {
			state.perms = perms
		}
	},
	actions: {
		async getUserInfo ({ commit }) {
			try {
				// 获取个人信息
				const user = await getUserProfileApi()
				if (!user?.data) {
					throw new Error('获取用户信息失败')
				}
				commit('setUserInfo', user.data)
				const [roleResult, customerResult, permsResult] = await Promise.allSettled([
					getUserRoleApi(user.data.userId),
					customerOpercustApi({ isTotal: true }),
					getPermsApi()
				])
				// 处理角色信息
				if (roleResult.status === 'fulfilled' && roleResult.value?.data) {
					commit('setRoles', roleResult.value.data)
				}
				// 处理客户信息
				if (customerResult.status === 'fulfilled' && customerResult.value?.data) {
					commit('setcustomerinfoInfo', customerResult.value.data)
				}
				// 处理按钮权限
				if (permsResult.status === 'fulfilled' && permsResult.value?.permissions) {
					commit('setPerms', permsResult.value.permissions)
				}
			} catch (err) {
				console.error('获取用户信息失败:', err)
			}
		},
		// 退出登录
		async logout ({ commit }) {
			await logoutApi()
			commit('quitLogin')
		}
	},
	plugins: [
		createPersistedState({
			key: 'logistics',
			paths: ['token', 'userinfo', 'custid', 'userid', 'customerinfo', 'roles', "perms", "isExternal"],
			storage: {
				getItem: (key) => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: (key) => uni.removeStorageSync(key),
			},
		}),
	],
})

export default store